/*
 *                    BioJava development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the individual
 * authors.  These should be listed in @author doc comments.
 *
 * For more information on the BioJava project and its aims,
 * or to join the biojava-l mailing list, visit the home page
 * at:
 *
 *      http://www.biojava.org/
 *
 * Created on 20.10.2009
 * @author Jonathan Warren
 *
 */package org.biojava.das.ucsc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.biojava.dasobert.dasregistry.Das1Validator;
import org.biojava.dasobert.dasregistry.DasCoordinateSystem;




public class UCSCCoordinateToRegistryCoordinates {
	List<DasCoordinateSystem> registryCoordinateSystems=null;
	List <Map<String,String>>ucscCoordinateSystemStrings=null;//store list of maps representing column names for all ucsc coordinate system
	public int coordinateSystemsFound=0;
	
	public UCSCCoordinateToRegistryCoordinates(){
		registryCoordinateSystems=this.getRegistryCoordinateSystems();
		ucscCoordinateSystemStrings=this.getUCSCDasCoordinateSystems();

	}
//	mysql -u genome -h genome-mysql.cse.ucsc.edu
//	use hgcentral;
//	select organism, scientificName,taxid, name,sourceName, defaultPos from dbDb;
	public DasCoordinateSystem chooseDasCoordinateSystem(String genomeString){
		
		DasCoordinateSystem coord=null;
		
		      for(Map <String,String>map:ucscCoordinateSystemStrings){
		    	  String name=map.get("name");
		    	  String scientificName=map.get("scientificName");
		    	  String taxid=map.get("taxid");
		    	  String sourceName=map.get("sourceName");
		    	  String defaultPos=map.get("defaultPos");
		    	    if(name.equals(genomeString)){
		    	    	System.out.println("name found="+name);
		    	    	coord=this.chooseCoordinate(genomeString, scientificName, taxid, sourceName, defaultPos);
		    	    }
		      }
		      
		  //get id as this is hg19 etc then look up the ucsc database to get the extra info
		//such as taxid, organism, and version (need class to do this).
		return coord;
	}
	
	
public List <Map<String,String>> getUCSCDasCoordinateSystems(){
		
	ucscCoordinateSystemStrings=new ArrayList();
		DasCoordinateSystem coord=new DasCoordinateSystem();
		Connection con=null;
		 try {
		      Class.forName("com.mysql.jdbc.Driver").newInstance();
		      con = DriverManager.getConnection("jdbc:mysql://genome-mysql.cse.ucsc.edu/hgcentral",
		        "genome", "");

		      PreparedStatement statment=con.prepareStatement("select organism, scientificName,taxid, name,sourceName, defaultPos from dbDb");
		      //statment.setString(1, genomeString);
		      ResultSet rs=statment.executeQuery();
		      while(rs.next()){
		    	  Map coordsInfo=new HashMap();
		    	  String name=rs.getString("name");
		    	  String scientificName=rs.getString("scientificName");
		    	  String taxid=rs.getString("taxid");
		    	  String sourceName=rs.getString("sourceName");
		    	  String defaultPos=rs.getString("defaultPos");
		    	  coordsInfo.put("name",name);
		    	  coordsInfo.put("scientificName",scientificName);
		    	  coordsInfo.put("taxid", taxid);
		    	  coordsInfo.put("sourceName",sourceName);
		    	  coordsInfo.put("defaultPos",defaultPos);
		    	  
		    	  ucscCoordinateSystemStrings.add(coordsInfo);
		    	  coordsInfo.toString();
		    	 // coord=this.chooseCoordinate(genomeString, scientificName, taxid, sourceName, defaultPos);
		      }
		      //if(!con.isClosed())
		        //System.out.println("Successfully connected to " +
		          //"MySQL server using TCP/IP...");

		    } catch(Exception e) {
		      System.err.println("Exception: " + e.getMessage());
		    } finally {
		      try {
		        if(con != null)
		          con.close();
		      } catch(SQLException e) {}
		    }
		  //get id as this is hg19 etc then look up the ucsc database to get the extra info
		//such as taxid, organism, and version (need class to do this).
		return ucscCoordinateSystemStrings;
	}
	
	
	
	public DasCoordinateSystem chooseCoordinate(String genomeString, String scientificName,String taxid, String sourceName, String defaultPos){
		DasCoordinateSystem coord=new DasCoordinateSystem();
		boolean coordFound=false;
		System.out.println("looking for:"+genomeString+"|"+scientificName+"|"+taxid+"|"+sourceName+"|"+defaultPos);
		for (int k = 0; k < registryCoordinateSystems.size(); k++) {
			DasCoordinateSystem tempCs = registryCoordinateSystems.get(k);
			if(tempCs.getOrganismName().equals(scientificName)){
				//System.out.println("organism sci name match");
				if(String.valueOf(tempCs.getNCBITaxId()).equals(taxid)){
					//System.out.println("potential match after taxid check:"+genomeString+"|"+scientificName+"|"+taxid+"|"+tempCs.getAuthority()+"|"+tempCs.getVersion()+"|"+tempCs.getCategory());
					if (tempCs.getAuthority().length()>3) {
						//System.out.println("sourceName="+sourceName);
						if (sourceName.contains(tempCs.getAuthority()
								.substring(0, 3))) {
							System.out
									.println("potential match after authority check:"
											+ genomeString
											+ "|"
											+ scientificName
											+ "|"
											+ taxid
											+ "|"
											+ tempCs.getAuthority()
											+ "|"
											+ tempCs.getVersion()
											+ "|"
											+ tempCs.getCategory());
							if (sourceName.contains(tempCs.getVersion())) {
								System.out.println("default position="
										+ defaultPos);
								String startOfTestCode = defaultPos.substring(
										0, 2);
								if (tempCs.getCategory().substring(0, 2)
										.equalsIgnoreCase(startOfTestCode)) {
									System.out.println("found:" + genomeString
											+ "|" + scientificName + "|"
											+ taxid + "|"
											+ tempCs.getAuthority() + "|"
											+ tempCs.getVersion() + "|"
											+ tempCs.getCategory());
									coordFound = true;
									coord = tempCs;
									//System.out.println("default position="+defaultPos);
									defaultPos=defaultPos.replace(",","");
									defaultPos=defaultPos.replace("-", ",");
									//System.out.println("altered position="+defaultPos);
									coord.setTestCode(defaultPos);
								}

							}
						}
					}
				}
				
			}
					

			}
		if(coordFound){
			coordinateSystemsFound++;
		}else{
			//System.out.println("not found");
		}
		return coord;
		
		
	}
	
	private List<DasCoordinateSystem> getRegistryCoordinateSystems(){
		Das1Validator dasvalidator=new Das1Validator();
		List<DasCoordinateSystem> registryCoordinateSystems=dasvalidator.getRegistryCoordinateSystems();
		return registryCoordinateSystems;
	}
	
}
